package com.corx.network.mysqlstorage.common;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author gx
 * @version 1.0.0
 */
public abstract class JdbcPagingSupport<T> {

    protected final JdbcTemplate jdbcTemplate;

    public JdbcPagingSupport(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    protected abstract RowMapper<T> getRowMapper();

    /**
     * 获取查询的总记录数
     */
    public long getTotalCount(String baseSql, Object[] params) {
        String countSql = "SELECT COUNT(*) FROM " +
            "(" + baseSql + ") AS temp";
        Long count = jdbcTemplate.queryForObject(countSql, Long.class, params);
        return count != null ? count : 0;
    }

    /**
     * 分页查询
     */
    public PageResult<T> findByPage(String baseSql, Object[] params, PageQuery pageQuery) {
        long total = getTotalCount(baseSql, params);

        // 如果没有数据，直接返回空结果，避免不必要查询
        if (total == 0) {
            return new PageResult<>(0, Collections.emptyList());
        }
        int offset = pageQuery.getOffset();
        int size = pageQuery.getPageSize();
        String paginatedSql = baseSql + " LIMIT ? OFFSET ?";

        List<Object> paramList = new ArrayList<>(Arrays.asList(params));
        paramList.add(size);
        paramList.add(offset);

        List<T> items = jdbcTemplate.query(paginatedSql, getRowMapper(), paramList.toArray());

        return new PageResult<>(total, items);
    }
}

